package encaps.action;

import encaps.entities.*;
import encaps.logging.JMSUtil;
import encaps.logging.Log;
import encaps.resources.Grants;
import encaps.resources.Image;
import encaps.resources.Labels;
import encaps.resources.Response;
import encaps.security.RoleManager;
import encaps.utils.*;
import java.sql.SQLException;
import java.util.Date;
import java.util.Map;
import javax.ejb.FinderException;
import javax.naming.NamingException;
import org.jdom.Element;

public class EditUserAction extends Action {

    public static final String EDIT_USER = "editUser";
    public static final String LOGIN = "login";
    public static final String PASSWORD = "pass";
    public static final String PASSWORD_REPEAT = "repass";
    public static final String INFO = "info";
    public static final String EMAIL = "email";
    public static final String CONTACTS = "contacts";
    public static final String PIC = "pic";
    public static final String ROLE = "role";
    protected static final String PASSWORD_MESSAGE = "passMsg";
    protected static final String PASSWORD_REPEAT_MESSAGE = "passRepeatMsg";
    protected ActionContext actionContext;

    public EditUserAction(ActionContext context, Grant requiredGrant) {
        this.requiredGrant = requiredGrant;
        actionContext = context;
    }

    @Override
    public Element execute() throws ActionExecutionException {
        try {
            Long id = Long.parseLong(actionContext.getTextParameter(ID));
            UserLocalHome userHome = EntityUtil.getUserHome();
            UserLocal user = userHome.findByPrimaryKey(id);
            String userLogin = user.getLogin();
            if (userLogin.equals(actionContext.getUserLogin())) {
                return XMLHelper.toXMLElement(user, Labels.getLabel(Labels.EDIT_PROFILE), RoleManager.getRoleManager().getRole(actionContext.getUserRole()), true);
            } else {
                Role role = RoleManager.getRoleManager().getRole(actionContext.getUserRole());
                Element result = createUserForm(user, role, null);
                JMSUtil.sendLogMessage(Log.UPDATE,
                        EntityUtil.getUserHome().findByLogin(actionContext.getUserLogin()).getID(),
                        actionContext.getUserLogin(), new Date(), User.TABLE_NAME,
                        user.getID(), user.getLogin());
                return result;
            }
        } catch (FinderException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        } catch (NamingException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        } catch (SystemException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        } catch (SQLException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        }
    }

    //Считывание данных в поля форм происходит из user, или, если user == null,
    //из validationMessages (используется в ApplyUserChangesAction)
    protected Element createUserForm(UserLocal user, Role role, Map<String, String> validationMessages) throws NamingException, FinderException, SQLException {
        Element response = XMLHelper.createElement(Response.RESPONSE);
        Element e = XMLHelper.addChild(response, Response.ENTITY);
        e.setAttribute(Response.EDIT, "true");

        String passMessage = null;
        String passRepeatMessage = null;

        String login, info, email, contacts, image, urole;
        Long id;
        if (user != null) {
            id = user.getID();
            login = user.getLogin();
            info = user.getInfo();
            email = user.getEmail();
            contacts = user.getContacts();
            image = user.getAvatar();
            urole = user.getRole();
        } else {
            id = Long.parseLong(validationMessages.get(ID));
            login = validationMessages.get(LOGIN);
            info = validationMessages.get(INFO);
            email = validationMessages.get(EMAIL);
            contacts = validationMessages.get(CONTACTS);
            image = validationMessages.get(PIC);
            passMessage = validationMessages.get(PASSWORD_MESSAGE);
            passRepeatMessage = validationMessages.get(PASSWORD_REPEAT_MESSAGE);
            urole = validationMessages.get(ROLE);
        }

        XMLHelper.addChild(e, XMLHelper.createHeader(String.format(Labels.getLabel(Labels.EDIT_USER_PROFILE_MESSAGE_PATTERN), login)));
        XMLHelper.addChild(e, XMLHelper.createImage(image, EditProfileAction.PICTURE));
        XMLHelper.addChild(e, XMLHelper.createPasswordField(Labels.getLabel(Labels.PASSWORD), PASSWORD, passMessage));
        XMLHelper.addChild(e, XMLHelper.createPasswordField(Labels.getLabel(Labels.REPEAT_PASSWORD), PASSWORD_REPEAT, passRepeatMessage));
        XMLHelper.addChild(e, XMLHelper.createTextArea(Labels.getLabel(Labels.INFO), info, INFO));
        XMLHelper.addChild(e, XMLHelper.createTextField(Labels.getLabel(Labels.EMAIL), email, EMAIL));
        XMLHelper.addChild(e, XMLHelper.createTextField(Labels.getLabel(Labels.CONTACTS), contacts, CONTACTS));

        String roles = Provider.getUniqueString(RoleGrantGenreEnum.ROLE, urole);
        XMLHelper.addChild(e, XMLHelper.createSelect(Labels.getLabel(Labels.ROLE), ROLE, roles, roles));

        XMLHelper.addChild(e, XMLHelper.createHiddenTextField(id, ID));

        if (role.hasGrant(Grants.EDIT_USER)) {
            XMLHelper.addChild(e, XMLHelper.createImageButton(Image.getImage(Image.APPLY), ApplyUserChangesAction.APPLY_USER_CHANGES));
        }
        JMSUtil.sendLogMessage(Log.UPDATE,
                EntityUtil.getUserHome().findByLogin(actionContext.getUserLogin()).getID(),
                actionContext.getUserLogin(), new Date(), User.TABLE_NAME,
                user.getID(), user.getLogin());
        return response;
    }
}
